package com.neusoft.SPNursingHome.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;

import com.neusoft.SPNursingHome.po.Client;
import com.neusoft.SPNursingHome.po.ClientCheckInDto;
import com.neusoft.SPNursingHome.po.ClientWithCareLevel;
import com.neusoft.SPNursingHome.po.ResponseBean;
import com.neusoft.SPNursingHome.service.ClientService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/client")
public class ClientController {

    @Resource
    @Autowired
    private ClientService clientService;

    //展示客户信息（默认自理）
    @PostMapping("/listAll")
    public ResponseBean<IPage<Client>> getClients(
            @RequestParam(defaultValue = "1") long pageNum,
            @RequestParam(defaultValue = "10") long pageSize,
            @RequestBody(required = false) Map<String, Object> query) {

        return clientService.findClientsByCriteria(pageNum, pageSize, query);
    }
    //逻辑删除单个客户
    @DeleteMapping("/deleteSingle/{clientId}")
    public ResponseBean<Void> deleteClient(@PathVariable Integer clientId) {
        // 将状态设置为 0 (删除)
        return clientService.updateClientStatus(clientId, 0);
    }

    //批量删除客户
    @PostMapping("/batch-delete")
    public ResponseBean<Void> deleteClientsBatch(@RequestBody List<Integer> clientIds) {
        return clientService.updateClientStatusBatch(clientIds, 0);
    }

    // 恢复单个客户
    @PostMapping("/restore/{clientId}")
    public ResponseBean<Void> restoreClient(@PathVariable Integer clientId) {
        // 将状态设置为 1 (正常)
        return clientService.updateClientStatus(clientId, 1);
    }

    // 获取单个客户详情用于编辑回显
    @GetMapping("/huixian/{clientId}")
    public ResponseBean<ClientCheckInDto> getClientDetails(@PathVariable Integer clientId) {
        return clientService.getClientDetailsForEdit(clientId);
    }

     // 更新客户信息
    @PutMapping("/updateClient")
    public ResponseBean<Void> updateClient(@RequestBody ClientCheckInDto dto) {
        return clientService.updateClientInfo(dto);
    }

     // 获取当前健康管家负责的客户列表
    @GetMapping("/my-clients")
    public ResponseBean<IPage<Client>> getMyClients(
            @RequestParam(defaultValue = "1") long pageNum,
            @RequestParam(defaultValue = "10") long pageSize,
            @RequestParam(required = true) Integer adId, // 从前端接收管家ID
            @RequestParam(required = false) String clientName) {

        return clientService.getMyManagedClients(pageNum, pageSize, adId, clientName);
    }
    //导出客户信息
    @GetMapping("/export")
    public void exportClients(HttpServletResponse response) {
        ResponseBean<byte[]> rb = clientService.exportAllClients();
        if (rb.getStatus() == 200 && rb.getData() != null) {
            try {
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding(StandardCharsets.UTF_8.name());
                String fileName = URLEncoder.encode("客户信息表", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
                response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

                response.getOutputStream().write(rb.getData());
                response.getOutputStream().flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                response.setStatus(500);
                response.setContentType("application/json");
                response.setCharacterEncoding(StandardCharsets.UTF_8.name());
                response.getWriter().println("{\"status\":500, \"msg\":\"" + rb.getMsg() + "\"}");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @GetMapping("/list")
    public ResponseBean<List<Client>> list() {
        return clientService.listAll();
    }

    @GetMapping("/unassigned")
    public ResponseBean<IPage<Client>> listUnassigned(
            @RequestParam(required = false) String name,
    @RequestParam(defaultValue = "1") long page,
    @RequestParam(defaultValue = "10") long size) {
        return clientService.listUnassignedCareClients(name, page, size);
    }

    @GetMapping("/{id}")
    public ResponseBean<Client> get(@PathVariable Integer id) {
        return clientService.getById(id);
    }

    @PostMapping("/create")
    public ResponseBean<Void> create(@RequestBody Client client) {
        return clientService.create(client);
    }

    @PutMapping("/update")
    public ResponseBean<Void> update(@RequestBody Client client) {
        return clientService.update(client);
    }

    @DeleteMapping("/delete/{id}")
    public ResponseBean<Void> delete(@PathVariable Integer id) {
        return clientService.delete(id);
    }

    // 设置客户护理级别
    @PostMapping("/setCareLevelId")
    public ResponseBean<Integer> setCareLevelId(Integer clientId, Integer careLevelId) {
        return clientService.setCareLevelId(clientId, careLevelId);
    }

    // 移除客户护理级别
    @PostMapping("/deleteCareLevelId")
    ResponseBean<Integer> deleteCareLevelId(Integer clientId) {
        return clientService.deleteCareLevelId(clientId);
    }

//    // 根据客户姓名查找客户且护理类型为“护理老人”
//    @GetMapping("/searchByNameAndCareType")
//    public ResponseBean<List<ClientWithCareLevel>> searchByNameAndCareType(@RequestParam String clientName) {
//        return clientService.searchByNameAndCareType(clientName, "护理老人");
//    }

    // 根据客户姓名查找客户且护理类型为“护理老人”
    @GetMapping("/searchByNameAndCareType")
    public ResponseBean<IPage<ClientWithCareLevel>> searchByNameAndCareType(@RequestParam String clientName, @RequestParam(defaultValue = "1") long page,
    @RequestParam(defaultValue = "10") long size) {
        return clientService.searchByNameAndCareType(clientName, "护理" , page, size);
    }

    // 根据客户姓名查找客户且护理类型为“护理老人”，且查询某个健康管家下的客户
    @GetMapping("/searchByNameAndCareTypeAndAdId")
    public ResponseBean<IPage<ClientWithCareLevel>> searchByNameAndCareTypeAndAdId(@RequestParam String clientName, @RequestParam Integer adId,@RequestParam(defaultValue = "1") long page,
    @RequestParam(defaultValue = "10") long size) {
        return clientService.searchByNameAndCareTypeAndAdId(clientName, "护理" , adId, page, size);
    }

}
